package dbhelper

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"sync"
)

var mysqlOncesync sync.Once
var mysqlHelperIns *MysqlHelper

func GetMysqlHelper() *MysqlHelper {
	mysqlOncesync.Do(func() {
		mysqlHelperIns = &MysqlHelper{}
		mysqlHelperIns.Init()
	})
	return mysqlHelperIns
}

type MysqlHelper struct {
}

func (this *MysqlHelper) Init() {
	mysqluser := beego.AppConfig.String("mysql_user")
	mysqlpass := beego.AppConfig.String("mysql_pass")
	mysqlhost := beego.AppConfig.String("mysql_host")
	mysqlport := beego.AppConfig.String("mysql_port")
	mysqldbname := beego.AppConfig.String("mysql_dbname")
	mysqlConStr := "" + mysqluser + ":" + mysqlpass + "@tcp(" + mysqlhost + ":" + mysqlport + ")/" + mysqldbname + "?charset=utf8"

	orm.RegisterDriver("mysql", orm.DRMySQL)

	orm.RegisterDataBase("default", "mysql", mysqlConStr)

	// create table
	orm.RunSyncdb("default", false, true)
}

func (this *MysqlHelper) GetNewOrm() orm.Ormer {
	newOrm := orm.NewOrm()
	return newOrm
}
